# -*- coding: utf-8 -*-
"""
author:码同学 极光
date:2025/3/22
desc: 
sample: 
"""
import logging
import os
import random
import time

import gevent
from locust import FastHttpUser, task

from exam.read_subject_table import query
from loucsttest.Login import sendEmail
from loucsttest.email_sender import EmailSender
from locust import HttpUser, task, constant, FastHttpUser, events
from locust.runners import WorkerRunner, STATE_STOPPING, STATE_STOPPED, STATE_CLEANUP

@events.init.add_listener
def on_locust_init(environment, runner, **_kwargs):
    if not isinstance(environment.runner, WorkerRunner):
        gevent.spawn(checker_login, environment)

is_quitting=False
def checker_login(environment, **kw):
    global is_quitting
    while not environment.runner.state in [STATE_STOPPING, STATE_STOPPED, STATE_CLEANUP]:
        print("checker-----")
        time.sleep(1)  # 需要等待系统启动注册
        if environment.runner.stats.total.fail_ratio > 0.01:
            logging.error("Test failed due to failure ratio > 1%")
            is_quitting = True
        elif environment.stats.total.avg_response_time > 500:
            logging.error(f"Test failed due to average response time ratio > 200ms,quitting")
            is_quitting = True
        elif environment.stats.total.get_response_time_percentile(0.95) > 500:
            logging.error(f"Test failed due to 95th percentile response time > 300, quitting")
            is_quitting = True

        if is_quitting:
            error_msg = {}
            error_msg['错误率'] = environment.runner.stats.total.fail_ratio
            error_msg['平均响应时间'] = str(int(environment.stats.total.avg_response_time)) + "ms"
            error_msg['top95'] = str(int(environment.stats.total.get_response_time_percentile(95))) + "ms"
            print(error_msg)
            sendEmail(title='登陆压测指标不满足需求', msg="当前指标：" + error_msg.__str__())
            # sendDingDing(msg="当前指标：" + error_msg.__str__())
            environment.runner.quit()
            return

class Login(FastHttpUser):
    host = "http://192.168.79.128:8085/"
    db_list = query('student') #只执行一次

    @task
    def login(self):
        url = '/exam/home/login'
        random_row = random.choice(self.db_list)
        #print(random_row)
        with self.client.post(url,
                         data={"name": random_row['name'], "password": random_row['password']},catch_response=True) as response:
            if response.status_code == 200:
                #print(response.json())
                if response.json()['type'] == 'success':
                    response.success()
                else:
                    print(response.status_code, random_row['name'], random_row['password'])
                    response.failure(response.json())
            else:
                print(response.status_code,random_row['name'],random_row['password'])
                response.failure(response.json())

if __name__ == '__main__':
    os.system('locust -f exam_login_loucst.py')

